package com.powernode.reggie.utils;

import java.util.Properties;
import java.util.Random;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
 * @description: 用于发送邮件验证码
 * @author: www
 * @time: 2023/3/15 14:45
 */
public class MailUtils {
    /**
     * 调用，传入发送对象邮箱即可发送一组随机的验证码
     * @param toEmail
     */
    public static void sendVerificationCode(String toEmail, String code) {
        String fromEmail = "3104652751@qq.com"; // 发送方邮箱地址
        String password = "duuzglqysayldfjh"; // 发送方邮箱密码  16位STMP口令
        String host = "smtp.qq.com"; // 发送方邮箱SMTP服务器地址
        int port = 587; // 发送方邮箱SMTP服务器端口号 都是587

        // 生成随机验证码
        //String code = generateCode();

        // 邮件主题和内容
        String subject = "reggie外卖-邮箱登录验证码";
        String content = "尊敬的用户你好！\r\n您的登录验证码为：: " + code + "（有效期一分钟，请勿告知他人）";

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        //props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);

        // 使用环境属性和授权信息，创建邮件会话 构建授权信息，用于进行SMTP进行身份验证
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(fromEmail, password);
            }
        });

        try {
            Message message = new MimeMessage(session); // 创建邮件消息对象
            message.setFrom(new InternetAddress(fromEmail));// 设置发件人
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));//设置收件人
            message.setSubject(subject);//设置邮件标题
            message.setContent(content,"text/html;charset=UTF-8");//设置邮件的正文
            Transport.send(message);//最后，发送邮件
            System.out.println("验证码 email sent successfully.");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    // 生成6位随机数字验证码
    public static String generateCode() {
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            builder.append(random.nextInt(10));
        }
        return builder.toString();
    }
}

